package cn.silver.module.authority.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.silver.framework.core.enums.SystemStatusEnums;
import cn.silver.framework.core.exception.ServiceException;
import cn.silver.framework.core.utils.MapstructUtils;
import cn.silver.framework.core.utils.StringUtils;
import cn.silver.framework.mybatis.service.impl.DataServiceImpl;
import cn.silver.framework.satoken.model.LoginUser;
import cn.silver.framework.satoken.utils.LoginHelper;
import cn.silver.module.authority.domain.SysRole;
import cn.silver.module.authority.domain.SysRoleDept;
import cn.silver.module.authority.domain.SysRoleMenu;
import cn.silver.module.authority.mapper.SysRoleMapper;
import cn.silver.module.authority.bean.RoleBean;
import cn.silver.module.authority.param.RoleParam;
import cn.silver.module.authority.service.ISysRoleDeptService;
import cn.silver.module.authority.service.ISysRoleMenuService;
import cn.silver.module.authority.service.ISysRoleService;
import cn.silver.module.system.domain.SysUserRole;
import cn.silver.module.system.enums.RoleTypeEnums;
import cn.silver.module.system.service.ISysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 角色 业务层处理
 *
 * @author Silver Zhou
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends DataServiceImpl<SysRoleMapper, SysRole, RoleParam, RoleBean> implements ISysRoleService {

    private final ISysUserRoleService roleService;
    private final ISysRoleDeptService deptService;
    private final ISysRoleMenuService menuService;

    @Override
    public String init() {
        List<SysRole> exists = this.baseMapper.selectList(new LambdaQueryWrapper<SysRole>().eq(SysRole::getBuilt, Boolean.TRUE));
        String result = exists.stream().filter(item -> RoleTypeEnums.SUPER_ROLE.getCode().equalsIgnoreCase(item.getType())).map(SysRole::getId).findFirst().orElse(null);
        if (StringUtils.isBlank(result)) {
            result = this.initRole(RoleTypeEnums.SUPER_ROLE);
        }
        exists = exists.stream().filter(item -> RoleTypeEnums.DEFAULT_ROLE.getCode().equalsIgnoreCase(item.getType())).toList();
        if (CollectionUtils.isEmpty(exists)) {
            this.initRole(RoleTypeEnums.DEFAULT_ROLE);
        }
        return result;

    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(String userId) {
        List<RoleBean> perms = baseMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (RoleBean perm : perms) {
            if (ObjectUtil.isNotNull(perm)) {
                permsSet.addAll(StringUtils.splitList(perm.getCode().trim()));
            }
        }
        return permsSet;
    }

    private String initRole(RoleTypeEnums enums) {
        SysRole role = SysRole.getInstance(enums);
        role.setSort(1);
        role.setBuilt(Boolean.TRUE);
        role.setId(IdUtil.getSnowflakeNextIdStr());
        this.baseMapper.insert(role);
        return role.getId();
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
//	@Override
    public List<String> selectRoleListByUserId(String userId) {
        return baseMapper.selectRoleListByUserId(userId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(RoleBean role) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getName, role.getName())
                .ne(ObjectUtil.isNotNull(role.getId()), SysRole::getId, role.getId()));
        return !exist;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(RoleBean role) {
        boolean exist = baseMapper.exists(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getCode, role.getCode())
                .ne(ObjectUtil.isNotNull(role.getId()), SysRole::getId, role.getId()));
        return !exist;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(RoleBean role) {
        if (LoginHelper.isSuperAdmin()) {
            return;
        }
        if (StringUtils.isNotBlank(role.getId()) && RoleTypeEnums.SUPER_ROLE.getCode().equalsIgnoreCase(role.getType())) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
        // 新增不允许使用 管理员标识符
        if (StringUtils.isBlank(role.getId()) && StringUtils.equalsAny(role.getType(), RoleTypeEnums.SUPER_ROLE.getCode(),
                RoleTypeEnums.DEFAULT_ROLE.getCode())) {
            throw new ServiceException("不允许创建系统内置角色!");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleId 角色id
     */
    @Override
    public void checkRoleDataScope(String roleId) {
        if (ObjectUtil.isNull(roleId)) {
            return;
        }
        if (LoginHelper.isSuperAdmin()) {
        }
//        List<RoleBean> roles = this.baseMapper.selectVoList(new LambdaQueryWrapper<SysRole>().eq(SysRole::getId, roleId));
//        if (CollUtil.isEmpty(roles)) {
//            throw new ServiceException("没有权限访问角色数据！");
//        }

    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public long countUserRoleByRoleId(String roleId) {
        return roleService.selectCount(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getId, roleId));
    }

    /**
     * 新增保存角色信息
     *
     * @param model 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean insert(RoleBean model) {
        this.checkRoleAllowed(model);
        Long count = this.selectExist(model);
        if (count > 0) {
            throw new ServiceException("新增角色'" + model.getName() + "'失败，角色信息已存在");
        }
        SysRole exist = StringUtils.isNotEmpty(model.getId()) ? this.baseMapper.selectById(model.getId()) : null;
        SysRole entity = MapstructUtils.convert(model, SysRole.class);
        if (exist != null) {
            baseMapper.updateById(entity);
        } else {
            entity.preInsert();
            model.setId(entity.getId());
            baseMapper.insert(entity);
        }
        this.menuService.save(model);
        this.deptService.save(model);
        return true;
    }

    /**
     * 修改保存角色信息
     *
     * @param model 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean update(RoleBean model) {
        this.checkRoleAllowed(model);
        if (!this.checkRoleNameUnique(model)) {
            throw new ServiceException("修改角色'" + model.getName() + "'失败，角色名称已存在");
        } else if (!this.checkRoleKeyUnique(model)) {
            throw new ServiceException("修改角色'" + model.getName() + "'失败，角色权限已存在");
        }
        // 删除角色与菜单关联
        this.menuService.save(model);
        this.deptService.save(model);
        this.cleanOnlineUserByRole(model.getId());
        return SqlHelper.retBool(baseMapper.updateById(MapstructUtils.convert(model, SysRole.class)));
    }

    /**
     * 修改角色状态
     *
     * @param roleId 角色ID
     * @param status 角色状态
     * @return 结果
     */
    @Override
    public int updateRoleStatus(String roleId, String status) {
        if (SystemStatusEnums.DISABLED.getCode().equals(status) && this.countUserRoleByRoleId(roleId) > 0) {
            throw new ServiceException("角色已分配，不能禁用!");
        }
        return baseMapper.update(null,
                new LambdaUpdateWrapper<SysRole>()
                        .set(SysRole::getStatus, status)
                        .eq(SysRole::getId, roleId));
    }

    /**
     * 修改数据权限信息
     *
     * @param bo 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int authDataScope(RoleBean bo) {
        // 删除角色与部门关联
        this.deptService.save(bo);
        return baseMapper.updateById(MapstructUtils.convert(bo, SysRole.class));
    }


    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean delete(String roleId) {
        // 删除角色与菜单关联
        this.menuService.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getId, roleId));
        // 删除角色与部门关联
        this.deptService.delete(new LambdaQueryWrapper<SysRoleDept>().eq(SysRoleDept::getId, roleId));
        return SqlHelper.retBool(baseMapper.deleteById(roleId));
    }

    /**
     * 批量删除角色信息
     *
     * @param ids 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public boolean deleteBatch(Collection<String> ids) {
        List<SysRole> roles = this.baseMapper.selectList(new LambdaQueryWrapper<SysRole>().in(SysRole::getId, ids));
        for (SysRole role : roles) {
//            checkRoleDataScope(roleId);
            checkRoleAllowed(BeanUtil.toBean(role, RoleBean.class));
            if (countUserRoleByRoleId(role.getId()) > 0) {
                throw new ServiceException(String.format("%1$s已分配，不能删除!", role.getName()));
            }
        }
        // 删除角色与菜单关联
        this.menuService.delete(new LambdaQueryWrapper<SysRoleMenu>().in(SysRoleMenu::getId, ids));
        // 删除角色与部门关联
        this.deptService.delete(new LambdaQueryWrapper<SysRoleDept>().in(SysRoleDept::getId, ids));
        return SqlHelper.retBool(baseMapper.deleteByIds(ids));
    }


    @Override
    public void cleanOnlineUserByRole(String roleId) {
        // 如果角色未绑定用户 直接返回
        Long num = roleService.selectCount(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getId, roleId));
        if (num == 0) {
            return;
        }
        List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
        if (CollUtil.isEmpty(keys)) {
            return;
        }
        // 角色关联的在线用户量过大会导致redis阻塞卡顿 谨慎操作
        keys.parallelStream().forEach(key -> {
            String token = StringUtils.substringAfterLast(key, ":");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
                return;
            }
            LoginUser loginUser = LoginHelper.getLoginUser(token);
            if (loginUser.getRoles().stream().anyMatch(r -> r.getId().equals(roleId))) {
                try {
                    StpUtil.logoutByTokenValue(token);
                } catch (NotLoginException ignored) {
                }
            }
        });
    }
}
